import { useUserStore } from '@/Stores/user';
import type { AnyObj, FormFieldValue, FormComponentType, FixedLengthArray } from './type';
import router from '@/Router';
import request from './request';
import { ElMessage, dayjs } from 'element-plus';

let permissioner: { hasPermission(code: string): Promise<boolean> };

/**
 * @author Elliot
 * @date 2023-04-18 17:45
 * @description 校验是否有权限
 * @param code 权限编码
 */
export const hasPermission = (code = ''): Promise<boolean> => {
	if (!permissioner) permissioner = useUserStore();
	return permissioner.hasPermission(code);
};

/**
 * @author Elliot
 * @date 2023-04-20 15:59
 * @description 验证手机号码正则
 * @param mobile 手机号
 */
export const checkMobile = (mobile: string) => {
	return (/^1[3|4|5|7|8|9][0-9]\d{4,8}$/.test(mobile));
};

/**
 *@description 臣信密码校验
 *@author Elliot 
 *@date 2023-07-27 10:03:40
 *@param string password 密码
*/
export const checkPassword = (password: string) => {
	if (password.length < 6) {
		return '密码至少6位数以上';
	}
	if (/\d+/.test(password) === false) {
		return '至少包含一个数字';
	}
	if (/[a-z]|[A-Z]/.test(password) === false) {
		return '至少包含一个英文字母';
	}
	return true;
};

/**
 *@description 
 *@author Elliot 
 *@date 2023-04-24 10:34
 *@description 根据传入的表单项类型，生成对应的空值
 *@param 
*/
export const getFormComponentEmptyByType = (config: FormComponentType, value?: FormFieldValue): FormFieldValue => {
	if (config.type) {
		if (['select', 'treeSelect'].includes(config.type)) {
			if (config.multiple) {
				return [];
			}
		}
		if (config.type === 'selectV2') {
			return null;
		}
		if (config.type === 'checkbox') {
			return [];
		}
		if (config.type === 'upload') {
			return [];
		}
		if (config.type === 'switch') {
			if (config.switch && 'inactiveValue' in config.switch) {
				return config.switch.inactiveValue;
			}
			return false;
		}
		if (config.type === 'inputNumber') {
			return 0;
		}
	}
	return '';
}

// 设置cookie
export const setCookie = (cname: string, cvalue: string | number, exdays = 1) => {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

// 获取cookie
export const getCookie = (cname = '') => {
	const name = cname + "=";
	const ca = document.cookie.split(';');
	for (let i = 0; i < ca.length; i++) {
		const c = ca[i].trim();
		if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
	}
	return "";
}

// 删除cookie
export const delCookie = (name = '') => {
	const exp = new Date();
	exp.setTime(exp.getTime() - 1);
	const cval = getCookie(name);
	console.log('cval: ', cval);
	if (cval != null) {
		document.cookie = name + "=" + cval + ";expires=" + exp.toString();
	}
}

// 获取url参数
export const getUrlQuery = (url = window.location.href) => {
	const queryStr = url.split('?')[1]
	if (queryStr) {
		return queryStr.split('&').reduce((query: AnyObj, item) => {
			const itemArr = item.split('=')
			query[itemArr[0]] = itemArr[1]
			return query
		}, {})
	}
	return {}
}

// url增加query参数
export const setUrlQuery = (
	{ url = window.location.href, query = {} }: { url: string; query: AnyObj }
) => {
	const urlNew = url.split('?')[0];
	const urlQuery = {
		...getUrlQuery(url),
		...query
	};
	const urlQueryKeys = Object.keys(urlQuery);
	return `${urlNew}${urlQueryKeys.length > 0 ? '?' : ''}${urlQueryKeys.map(key => `${key}=${urlQuery[key]}`).join('&')}`;
}

// 获取对象属性，即该对象的某个字段在未来某个时间段被赋值，赋值后执行callbak
export const getObjValByKey = (
	{
		obj = {}, key = '', callback, valType, count = 1, maxCount = 100
	}
		:
		{
			obj: AnyObj; key: string; callback?: Function; valType?: 'Array' | 'Object' | 'String'; count?: number; maxCount?: number;
		}
) => {
	if (!key) {
		typeof callback === 'function' && callback(false);
		return;
	}
	if (key in obj && obj[key]) {
		if (valType) {
			if (valType === 'Array') {
				if (Array.isArray(obj[key]) && obj[key].length > 0) {
					typeof callback === 'function' && callback(obj[key]);
					return;
				}
			}
		} else {
			// console.log('true');
			typeof callback === 'function' && callback(obj[key]);
			return;
		}
	}
	// console.log('count: ', count);
	if (count > maxCount) {
		typeof callback === 'function' && callback(false);
		return;
	}
	setTimeout(() => {
		getObjValByKey({ obj, key, valType, count: count + 1, callback })
	}, 10);
}

// 去掉所有的html标记
function delHtmlTag(str = '') {
	if (str) return str.replace(/<[^>]+>/g, "")  //正则去掉所有的html标记
	return '';
}

// 处理html()方法返回特殊符号的转义问题
export function escapeHtml(str = '') {
	let temp = "";
	if (str.length == 0) return ""
	temp = str.replace(/&amp;/g, "&");
	temp = temp.replace(/&lt;/g, "<");
	temp = temp.replace(/&gt;/g, ">");
	temp = temp.replace(/&nbsp;/g, " ");
	temp = temp.replace(/&#39;/g, "\'");
	temp = temp.replace(/&quot;/g, "\"");
	return temp;
}

// 获取纯文本
export function getText(val = '') {
	if (val) {
		return escapeHtml(delHtmlTag(val)).trim();
	}
	return '';
}

/**
 *@description 生成uuid
 *@author Elliot 
 *@date 2023-06-17 15:35:30
*/
export const createUuid = () => {
	const s = [];
	const chars = "0123456789abcdefghijklmnopqrstuvwxyz";
	for (let i = 0; i < chars.length; i++) {
		s[i] = chars.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4";
	s[19] = chars.substr((parseInt(s[19]) & 0x3) | 0x8, 1);
	s[8] = s[13] = s[18] = s[23] = "-";
	return s.join("");
}

/**
 *@description 生成英文uuid
 *@author Elliot 
 *@date 2023-06-17 15:35:30
*/
export const createEnglishUuid = () => {
	const s = [];
	const chars = "abcdefghijklmnopqrstuvwxyz";
	for (let i = 0; i < chars.length; i++) {
		s[i] = chars.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4";
	s[19] = chars.substr((parseInt(s[19]) & 0x3) | 0x8, 1);
	s[8] = s[13] = s[18] = s[23] = "-";
	return s.join("");
}

/**
 *@description 生成数字uuid
 *@author Elliot 
 *@date 2023-07-21 13:42:30
*/
export const createNumberUuid = () => {
	const s = [];
	const chars = "0123456789";
	for (let i = 0; i < 12; i++) {
		s[i] = chars.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4";
	s[19] = chars.substr((parseInt(s[19]) & 0x3) | 0x8, 1);
	// console.log('s: ', s);
	return Number(s.join(""));
}

// 加载阿里云播放SDK
export const loadAliVedioJs = (): Promise<Boolean> => {
	return new Promise((resolve, reject) => {
		if (document.getElementById('aliplayer')) {
			resolve(true);
		} else {
			if (!document.getElementById('aliplayer-css')) {
				const head = document.getElementsByTagName('head')[0];
				const link = document.createElement('link');
				link.id = 'aliplayer-css';
				link.rel = 'stylesheet';
				link.type = 'text/css';
				link.href = 'https://g.alicdn.com/de/prismplayer/2.9.7/skins/default/aliplayer-min.css';
				head.appendChild(link);
			}

			const script = document.createElement("script");
			script.type = 'text/javascript';
			script.charset = 'utf-8';
			script.onload = () => {
				resolve(true);
			}
			script.onerror = () => {
				reject(false);
			}
			script.id = 'aliplayer';
			// script.src = 'https://g.alicdn.com/de/prismplayer/2.15.2/aliplayer-h5-min.js';
			script.src = 'https://g.alicdn.com/de/prismplayer/2.9.7/aliplayer-min.js';

			document.body.appendChild(script);
		}
	})
};

// 加载js文件
export const loadJs = (link = '') => {
	return new Promise((resolve, reject) => {
		if (link) {
			const script = document.createElement("script");
			script.type = 'text/javascript';
			script.charset = 'utf-8';
			script.onload = () => {
				resolve(true);
			}
			script.onerror = () => {
				reject(false);
			}
			script.id = 'aliplayer';
			script.src = link;
			document.body.appendChild(script);
		} else {
			reject()
		}
	})
};

// 小于10则返回'0Value'
export const getValueDateBy = (value = 1) => {
	if (value < 10) {
		if (value > 0) {
			return `0${value}`;
		}
		return '00';
	}
	return value;
};

/**
 *@description 下载文件
 *@author Elliot 
 *@date 2023-07-05 10:13:53
 *@param {string} fileUrl 文件链接地址
*/
export const downloadFile = (fileUrl: string = '') => {
	const iframe = document.createElement("iframe");
	// 防止影响页面布局
	iframe.style.display = "none";
	iframe.style.height = '0px';
	iframe.src = fileUrl;
	document.body.appendChild(iframe);
	iframe.onload = () => {
		// console.log('success');
		document.body.removeChild(iframe);
	};
	iframe.onerror = (error) => {
		// console.log('error: ', error);
		document.body.removeChild(iframe);
	}
};

/**
 *@description 判断是否为链接
 *@author Elliot 
 *@date 2023-06-28 16:37:39
 *@param url 链接
*/
export const isUrl = (url = '') => {
	return url && /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/.test(url) && url.indexOf(',') === -1;
};

/**
 *@description 是否为图片链接
 *@author Elliot 
 *@date 2023-08-10 14:31:44
 *@param string url
*/
export const isImgUrl = (url = '') => {
	return isUrl(url) && /.(jpg|png|bmp|jpeg|svg|gif|webp)$/.test(url);
};

// 图片链接匹配正则
export const imgSrcReg = /<img.*? src=('|")?([^'"]+)('|")?([^>]+>)/gim;

// 返回图片标签数组
export const getImgTag = (str = '') => {
	return str.match(imgSrcReg);
};

// 生成获取标签属性值正则
export const getAttrReg = (tag = 'src') => {
	return new RegExp(`${tag}=('|"){1,1}[^'"]+('|"){1,1}`, 'gim');
};

// 添加属性
export const addTagAttr = ({ tag = '', tagName = 'src', tagVal = '', }) => {
	if (tagVal && tag) {
		let str = '';
		str = tag.replace('/>', ` ${tagName}="${tagVal}" />`);
		str = tag.replace('>', ` ${tagName}="${tagVal}" />`);
		return str;
	}
	return '';
};

// 获取标签正则表达式
export const getTag = ({ tagName = '' }) => {
	if (tagName === 'img') {
		return new RegExp(`<img .*?>`, 'gm');
	}
	return new RegExp(`<${tagName} .*?>.*?</${tagName}>`, 'gm');
}

/**
 *@description 删除标签属性
 *@author Elliot 
 *@date 2023-07-07 16:51:06
 *@param {string} tag 标签指
 *@param {string} tagName 标签名称
 *@param {string} attrName 属性名称
*/
export const delTagAttr = ({ tag = '', tagName = 'img', attrName = 'src' } = {}) => {
	if (getTag({ tagName }).test(tag)) { // 校验是否为标签
		if (tag.includes(`${attrName}=`)) {
			return tag.replace(new RegExp(` ${attrName}=('|")?([^'"]+)('|")`, 'gi'), '');
		}
	}
	return tag;
};

// 获取图片标签reg
export const imgTagReg = /<img.*? src=('|")?([^'"]+)('|")?([^>]+>)/gim;

/**
 *@description 设置html里的图片懒加载属性
 *@author Elliot
 *@date 2023-12-08 14:59:28
 *@param htmlContent，html文本内容
*/
export const setImgLazyLoadStr = ({ htmlContent = '' } = {}) => htmlContent.replace(imgTagReg, imgStr => {
	if (imgStr.toLowerCase().includes('data-src=')) {
		return imgStr;
	}
	const src = imgSrcReg.exec(imgStr);
	if (src) {
		const resultTag = addTagAttr({ tagVal: src[2].replace(/("|')?/g, ''), tag: imgStr, tagName: 'data-src' });
		return delTagAttr({ tag: resultTag, tagName: 'img', attrName: 'src' });
	}
	return '';
});

// 匹配数字字符串正则
export const numbersReg = /\d+\.?\d+/;

// 日期匹配
export const dateReg = /(\d{4})-(\d{2})-(\d{2})/;

// 日期时间匹配
export const dateTimeReg = /(\d{4})-(\d{2})-(\d{2})\s(\d){2}:(\d){2}(:(\d){2})?/;

// 上传文件，uploadFile
export const uploadFile = ({ accept = 'image/*', multiple = 1 }: { accept?: string; multiple?: number } = { accept: 'image/*' }): Promise<File[]> => {
	return new Promise((resolve, reject) => {
		let inputDom = document.getElementById('upload-file-elliot') as any;
		if (!inputDom) {
			inputDom = document.createElement('input');
			inputDom.setAttribute('type', 'file');
			inputDom.style.display = 'none';
			inputDom.setAttribute('id', 'upload-file-elliot');
			document.body.appendChild(inputDom);
		} else {
			inputDom.outerHTML = inputDom.outerHTML;
		}
		if (accept === 'doc') {
			accept = '.doc,.pdf,.docx,.xls,.xlsx,.ppt,.pptx,.excel,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document';
		}
		inputDom.setAttribute('accept', accept);
		inputDom.setAttribute('multiple', multiple);
		inputDom.click();
		inputDom.onchange = () => resolve(inputDom.files);
		inputDom.onerror = (err: any) => reject(err);
	});
};

/**
 *@description 文件下载多种处理
 *@author Elliot 
 *@date 2023-08-14 13:59:43
*/
export const DownloadFileTools = {
	/**
	   * @description: base64对象转blob文件对象
	   * @param urlData  ：数据的base64对象
	   * @param type  ：类型 png,pdf,doc,mp3等;
	   * @returns {Blob}：Blob文件对象
	   */
	base64ToBlob(urlData = '', type = '') {
		let arr = urlData.split(',');
		let array = arr[0].match(/:(.*?);/);
		let mime = (array && array.length > 1 ? array[1] : type) || type;
		// 去掉url的头，并转化为byte
		let bytes = window.atob(arr[1]);
		// 处理异常,将ascii码小于0的转换为大于0
		let ab = new ArrayBuffer(bytes.length);
		// 生成视图（直接针对内存）：8位无符号整数，长度1个字节
		let ia = new Uint8Array(ab);
		for (let i = 0; i < bytes.length; i++) {
			ia[i] = bytes.charCodeAt(i);
		}
		return new Blob([ab], {
			type: mime
		});
	},
	/**
	 * @description: 下载导出文件
	 * @param blob  ：返回数据的blob对象或链接
	 * @param fileName  ：下载后文件名标记
	 * @param fileType  ：文件类 word(docx) excel(xlsx) ppt等
	 */
	downloadExportFile(blob: Blob, fileName = '', fileType = '') {
		let downloadElement = document.createElement('a');
		let href = '';
		if (typeof blob == 'string') {
			downloadElement.target = '_blank';
		} else {
			href = window.URL.createObjectURL(blob); //创建下载的链接
		}
		downloadElement.href = href;
		downloadElement.download = fileName + '.' + fileType; //下载后文件名
		document.body.appendChild(downloadElement);
		downloadElement.click(); //触发点击下载
		document.body.removeChild(downloadElement); //下载完成移除元素
		if (typeof blob != 'string') {
			window.URL.revokeObjectURL(href); //释放掉blob对象
		}
	},

	/**
	 * @description: base64转文件并下载
	 * @param string base64 : base64数据
	 * @param string fileName {String} : 文件名
	 * @param string fileType {String} : 要导出的文件类型png,pdf,doc,mp3等
	 */
	downloadFileByBase64(base64 = '', fileName = '', fileType = '') {
		let blob = this.base64ToBlob(base64, fileType)  // 转成blob对象
		this.downloadExportFile(blob, fileName, fileType) // 下载文件
	}
}

export const routerBack = () => {
	router.back();
};

export const isObject = (obj: any) => Object.prototype.toString.call(obj) === '[object Object]';

// 生成随机数
export const getRandomNum = (min = 1, max = 10) => Math.floor(Math.random() * (max - min + 1) + min);

// 上传本地文件到服务器
export const uploadFileToServer = async ({ file, setFormDataFn }: { file: File, setFormDataFn?: Function }) => {
	const formData = new FormData();
	formData.append('file', file);
	setFormDataFn && setFormDataFn(formData);
	// console.log('formData: ', formData);
	// console.log('file: ', file);
	const { url = '' } = await request({
		url: '/user/file/upload?code=WOS&public=true&server=1',
		method: 'post',
		// contentTypeIsForm: true,
		headers: {
			'Content-Type': 'multipart/form-data; boundary=----;'
		},
		errorToast: true,
		showLoading: {},
		data: formData
	});
	return url;
};

// 防抖动函数
// export function debounce(fn: Function, wait = 50, immediate = true) {
//     let timer: any;
//     return function() {
//         if(immediate) {
//             fn.apply(this, arguments);
//         }
//         if(timer) clearTimeout(timer)
//         timer = setTimeout(()=> {
//             fn.apply(this, arguments);
//         }, wait)
//     }
// }

/**
 * 复制文本
 * @param {String} value 需要复制的文本
 */
export const copyText = async (value: string = '') => {
	if (!value) {
		return ElMessage({
			message: '无复制内容',
			type: 'warning'
		});
	}
	// 判断当前环境是否支持navigator.clipboard 对象
	if (navigator.clipboard && window.isSecureContext) {
		try {
			await navigator.clipboard.writeText(value);
			ElMessage({
				message: '复制成功',
				type: 'success'
			});
			return true;
		} catch (error) {
			ElMessage({
				message: '复制失败',
				type: 'warning'
			});
			return false;
		}
	}
	// 动态创建 textarea 标签
	const textarea = document.createElement('textarea');
	// 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘
	textarea.setAttribute('readonly', '1');
	// 将要 copy 的值赋给 textarea 标签的 value 属性
	textarea.setAttribute('value', value);
	// 将 textarea 插入到 body 中
	document.body.appendChild(textarea);
	// 选中值并复制
	textarea.focus();
	textarea.setSelectionRange(0, textarea.value.length);
	const result = document.execCommand('copy');
	// 操作完成后删除标签
	document.body.removeChild(textarea);
	ElMessage({
		message: result ? '复制成功' : '复制失败',
		type: result ? 'success' : 'warning'
	});
};

// 将blob格式的数据下载为文件
export const downloadBlobFile = (blob: Blob, fileName = '') => {
	const aTag = document.createElement('a');
	aTag.style.display = 'none';
	aTag.download = fileName;
	const link = URL.createObjectURL(blob);
	aTag.href = link;
	document.body.appendChild(aTag);
	aTag.click();
	document.body.removeChild(aTag);
	ElMessage({
		message: '执行下载',
		type: 'success'
	});
};

/**
 * 处理秒，大于等于60秒返回X时X秒，小于60返回X秒
 * @param second 年份，number
 * @returns text，string
 */
export const secondToText = (second = 0) => {
	if (second >= 60) {
		const secondText = second % 60 > 0 ? `${second % 60}秒` : ''
		return `${Math.floor(second / 60)}分${secondText ? '' : '钟'}${secondText}`
	}
	return `${second}秒`
};

/**
 * 阿拉伯数字转中文数字,
 * 如果传入数字时则最多处理到21位，超过21位js会自动将数字表示成科学计数法，导致精度丢失和处理出错
 * 传入数字字符串则没有限制
 * @param {number|string} digit
 */
export function toZhDigit(digit: string | number) {
	digit = typeof digit === 'number' ? String(digit) : digit;
	const zh = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
	const unit = ['千', '百', '十', ''];
	const quot = ['万', '亿', '兆', '京', '垓', '秭', '穰', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祗', '那由他', '不可思议', '无量', '大数'];

	let breakLen = Math.ceil(digit.length / 4);
	let notBreakSegment = digit.length % 4 || 4;
	let segment: any;
	let zeroFlag = [], allZeroFlag = [];
	let result = '';

	while (breakLen > 0) {
		if (!result) { // 第一次执行
			segment = digit.slice(0, notBreakSegment);
			let segmentLen = segment.length;
			for (let i = 0; i < segmentLen; i++) {
				if (segment[i] != 0) {
					if (zeroFlag.length > 0) {
						result += '零' + zh[segment[i]] + unit[4 - segmentLen + i];
						// 判断是否需要加上 quot 单位
						if (i === segmentLen - 1 && breakLen > 1) {
							result += quot[breakLen - 2];
						}
						zeroFlag.length = 0;
					} else {
						result += zh[segment[i]] + unit[4 - segmentLen + i];
						if (i === segmentLen - 1 && breakLen > 1) {
							result += quot[breakLen - 2];
						}
					}
				} else {
					// 处理为 0 的情形
					if (segmentLen == 1) {
						result += zh[segment[i]];
						break;
					}
					zeroFlag.push(segment[i]);
					continue;
				}
			}
		} else {
			segment = digit.slice(notBreakSegment, notBreakSegment + 4);
			notBreakSegment += 4;

			for (let j = 0; j < segment.length; j++) {
				if (segment[j] != 0) {
					if (zeroFlag.length > 0) {
						// 第一次执行zeroFlag长度不为0，说明上一个分区最后有0待处理
						if (j === 0) {
							result += quot[breakLen - 1] + zh[segment[j]] + unit[j];
						} else {
							result += '零' + zh[segment[j]] + unit[j];
						}
						zeroFlag.length = 0;
					} else {
						result += zh[segment[j]] + unit[j];
					}
					// 判断是否需要加上 quot 单位
					if (j === segment.length - 1 && breakLen > 1) {
						result += quot[breakLen - 2];
					}
				} else {
					// 第一次执行如果zeroFlag长度不为0, 且上一划分不全为0
					if (j === 0 && zeroFlag.length > 0 && allZeroFlag.length === 0) {
						result += quot[breakLen - 1];
						zeroFlag.length = 0;
						zeroFlag.push(segment[j]);
					} else if (allZeroFlag.length > 0) {
						// 执行到最后
						if (breakLen == 1) {
							result += '';
						} else {
							zeroFlag.length = 0;
						}
					} else {
						zeroFlag.push(segment[j]);
					}

					if (j === segment.length - 1 && zeroFlag.length === 4 && breakLen !== 1) {
						// 如果执行到末尾
						if (breakLen === 1) {
							allZeroFlag.length = 0;
							zeroFlag.length = 0;
							result += quot[breakLen - 1];
						} else {
							allZeroFlag.push(segment[j]);
						}
					}
					continue;
				}
			}
			--breakLen;
		}
		return result;
	}
};

// 同步等待X秒
export const setTimeoutAsync = (timeout = 10) => new Promise(resolve => setTimeout(resolve, timeout));

// 蹦床函数，用于递归，防止内存溢出
export function tco(f: Function): any {
	let value: any;
	let active = false;
	const accumulated: any[] = [];

	return function accumulator(this: any, ..._args: any[]) {
		accumulated.push(_args);
		if (!active) {
			active = true;
			while (accumulated.length) {
				value = f.apply(this, accumulated.shift());
			}
			active = false;
			return value;
		}
	};
}

/**
 *@description 判断多个时间段是否重复
 *@author Elliot
 *@date 2023-12-16 13:58:03
 *@param times 二维数组，每项是长度为2的字符串数组
*/
export const isRepetitiveTime = (times: FixedLengthArray<string , 2>[]): boolean => {
	return times.some((range, index: number) => {
		// console.log('range: ', range);
		if (!range[0] || !range[1]) {
			return false;
		}
		const startTimeTimestamp = dayjs(range[0]).valueOf();
		const endTimeTimestamp = dayjs(range[1]).valueOf();
		if (!Number.isNaN(startTimeTimestamp)) {
			if (startTimeTimestamp === endTimeTimestamp) {
				return true;
			}
			return times.some((itemNext: (string | Date)[], indexNext: number) => {
				if (!itemNext[0] || !itemNext[1]) {
					return false;
				}
				if (index != indexNext) {
					const startTimeNext = dayjs(itemNext[0]).valueOf();
					const endTimeNext = dayjs(itemNext[1]).valueOf();
					// console.log('startTimeNext: ', dayjs(startTimeNext).format('YYYY-MM-DD HH:mm:ss'));
					// console.log('endTimeNext: ', dayjs(endTimeNext).format('YYYY-MM-DD HH:mm:ss'));
					if (!Number.isNaN(startTimeNext) && !Number.isNaN(endTimeNext)) {
						if (startTimeTimestamp >= startTimeNext && startTimeTimestamp <= endTimeNext) {
							return true;
						}
						if (endTimeTimestamp >= startTimeNext && endTimeTimestamp <= endTimeNext) {
							return true;
						}
						if (startTimeTimestamp <= startTimeNext && endTimeTimestamp >= endTimeNext) {
							return true;
						}
					}
				}
				return false;
			});
		}
		return false;
	})
};

// 处理大纲树每项数据
export const handleLMSCategoryTree = (treeItem: any) => {
	return {
		...treeItem,
		disabled: treeItem.isBloc == 0,
		children: (treeItem.children || []).map(handleLMSCategoryTree)
	}
};

export const clearUserInfo = () => {
	delCookie("userId");
	delCookie("token");
};

export const onNoLogin = () => {
	clearUserInfo();
	router.push({
		path: '/login',
		name: 'Login'
	});
};

export const getInlineStrHtml = (html: string) => {
	if (!html) return '';
	html = html.replace(/^\<p\>/, '');
    html = html.replace(/\<\/p\>$/, '');
    return html;
};

export const baseURL = process.env.VITE_BASE_URL;

export const lineBaseURL = "http://8.129.10.102:8080";

// base64转文件流
export function dataURLtoFile(dataurl: any, filename: string) {
	let arr = dataurl.split(',')
	let mime = arr[0].match(/:(.*?);/)[1]
	let bstr = atob(arr[1])
	let n = bstr.length
	let u8arr = new Uint8Array(n)
	while (n--) {
	  u8arr[n] = bstr.charCodeAt(n)
	}
	return new File([u8arr], filename, { type: mime });
}

// 退出登陆
export const logout = () => {
	delCookie("userId");
	delCookie("token");
	router.push({
		path: '/login',
		name: 'Login'
	});
};